/**
 * VUEshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.vueshop.com.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: soubao-java 2020-07-22 $
 */<template>
  <div>
    <div>
      <div class="fixed-bar">
        <div class="item-title">
          <router-link
            class="back"
            :to="{name:'goods_types',params:{currentPage:$route.params.currentPage}}"
            title="返回列表"
          >
            <i class="fa fa-arrow-circle-o-left"></i>
          </router-link>
          <div class="subject">
            <h3>模型管理 - 添加修改模型</h3>
            <h5>添加修改模型</h5>
          </div>
        </div>
        <div
          id="explanation"
          class="explanation"
          style="color: rgb(85, 85, 85); background-color: rgb(243, 244, 244); width: 98%; height: 100%;"
        >
          <div class="bckopa-tips">
            <div class="title">
              <img src="@/static/images/handd.png" alt />
              <h4 title="提示相关设置操作时应注意的要点">操作提示</h4>
            </div>
            <ul>
              <li>商品模型是用来规定某一类商品共有规格和属性的集合，其中规格会影响商品价格，同一个商品不同的规格价格会不同，而属性仅仅是商品的属性特质展示</li>
              <li>商品模型用于管理某一类商品的规格、属性</li>
              <li>发布某一个商品时，选中商品分类,如果该商品分类绑定了某个商品模型,那么该商品就有这个模型的所有规格和属性</li>
            </ul>
          </div>
          <span title="收起提示" id="explanationZoom" style="display: block;"></span>
        </div>
      </div>
      <div class="ncap-form-default">
        <dl class="row">
          <dt class="tit">
            <label>
              <em>*</em>模型名称
            </label>
          </dt>
          <dd class="opt">
            <el-input v-model="goods_type.name" placeholder="请输入模型名称" size="small"></el-input>
            <p class="err-msg" v-if="errResult.name && !goods_type.name">{{errResult.name}}</p>
          </dd>
        </dl>
        <dl class="row">
          <dt class="tit">
            <label>
              <em>*</em>绑定分类
            </label>
          </dt>
          <dd class="opt">
            <div v-for="(item,index) in goods_type.goods_category_list" :key="index">
              <el-cascader
                v-model="item.parent_ids"
                :options="goodsCatCascade"
                :props="{ label: 'name', value: 'id' }"
                size="small"
              ></el-cascader>
              <el-button
                slot="append"
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="deleteBindGoodsCat(index, goods_type.goods_category_list)"
              ></el-button>
            </div>
            <el-button
              type="primary"
              @click="addBindGoodsCat()"
              icon="el-icon-plus"
              size="small"
            >新增绑定分类</el-button>
            <p
              class="err-msg"
              v-if="errResult.goods_category_list && !goods_type.goods_category_list"
            >{{errResult.goods_category_list}}</p>
          </dd>
        </dl>
        <dl class="row">
          <dt class="tit">
            <label>规格设置</label>
          </dt>
          <dd class="opt">
            <el-table :data="goods_type.spec_list" style="width: 50%" border>
              <el-table-column label="排序" width="100" class-name="sort-input">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.order" placeholder="请输入内容" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="规格名称" width="200" class-name="name-input">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.name" placeholder="请输入内容" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="是否可上传规格图" width="150">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.is_upload_image"
                    :active-value="1"
                    :inactive-value="0"
                  ></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="deleteSpec(scope.$index, goods_type.spec_list)"
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" @click="addBindSpec" icon="el-icon-plus" size="small">新增规格</el-button>
          </dd>
        </dl>
        <dl class="row">
          <dt class="tit">
            <label>属性设置</label>
          </dt>
          <dd class="opt">
            <el-table :data="goods_attribute_select" style="width: 90%" border>
              <el-table-column label="排序" width="100" class-name="sort-input">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.order" placeholder="请输入内容" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="属性名称" width="200" class-name="name-input">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.attr_name" placeholder="请输入内容" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="是否显示" width="150">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.attr_index" :active-value="1" :inactive-value="0"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="属性值" width="450">
                <template slot-scope="scope">
                  <el-tag
                    :key="attribute"
                    v-for="attribute in scope.row.attr_value_list"
                    closable
                    :disable-transitions="false"
                    @close="deleteAttributeVal(scope.$index, attribute)"
                  >{{attribute}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.$index)"
                    @blur="handleInputConfirm(scope.$index)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.$index)"
                  >+ 新增属性值</el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="deleteAttribute(scope.$index, goods_attribute_select)"
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              type="primary"
              @click="addAttributeSelect"
              icon="el-icon-plus"
              size="small"
            >新增属性</el-button>
          </dd>
        </dl>
        <dl class="row">
          <dt class="tit">
            <label>自定义属性设置</label>
          </dt>
          <dd class="opt">
            <el-table :data="goods_attribute_input" style="width: 50%" border>
              <el-table-column label="排序" width="100" class-name="sort-input">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.order" placeholder="请输入内容" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="属性名称" width="200" class-name="name-input">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.attr_name" placeholder="请输入内容" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="是否显示" width="150">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.attr_index" :active-value="1" :inactive-value="0"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="deleteAttribute(scope.$index, goods_attribute_input)"
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              type="primary"
              @click="addAttributeInput"
              icon="el-icon-plus"
              size="small"
            >新增自定义属性</el-button>
          </dd>
        </dl>
        <dl class="row">
          <dt class="tit">
            <label>品牌</label>
          </dt>
          <dd class="opt">
            <el-checkbox-group v-model="brand_ids">
              <div v-for="(goods_cat,goods_cat_int) in goods_category_brand" :key="goods_cat_int">
                <span>商品分类:{{goods_cat.name}}</span>
                <el-checkbox
                  v-for="(brand,brand_index) in goods_cat.brands"
                  :key="brand_index"
                  :label="brand.id"
                >{{brand.name}}</el-checkbox>
              </div>
            </el-checkbox-group>
          </dd>
        </dl>
        <div class="bot">
          <el-button type="success" @click="submit()" :loading="isLoading">确认提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import mixins from "@/mixins/inside.js";
import {
  updateGoodsType,
  addGoodsType,
  getGoodsCategoryTree,
  deleteBindGoodsCat,
  deleteAttribute,
  getGoodsCatBrands,
  getGoodsType,
  deleteSpec
} from "@/utils/api";
export default {
  mixins: [mixins], //混入判断是否传参  是否需要返回上一页
  data() {
    return {
      goods_type: {
        goods_category_list: [],
        spec_list: []
      },
      goods_attribute_select: [], //商品模型绑定的属性
      goods_attribute_input: [], //商品模型绑定的属性
      brand_ids: [], //商品模型绑定的品牌id数组

      goods_category_brand: [], //商品分类的商品品牌
      goodsCatCascade: [], //商品分类
      brands: [], //商品品牌
      inputValue: "",
      errResult: {},
      isLoading: false
    };
  },
  created() {
    if (typeof this.$route.params.id != "undefined") {
      //编辑
      this.getGoodsType(this.$route.params.id);
    } else {
      //添加
    }
    this.getGoodsCatCascade();
    this.getGoodsCatBrands();
  },
  components: {},
  methods: {
    submit() {
      var that = this;
      this.goods_type.goods_attributes = this.goods_attribute_select.concat(
        this.goods_attribute_input
      );
      this.goods_type.brand_type_list = [];
      this.brand_ids.forEach(function(item, index) {
        var brand_type = new Object();
        brand_type.brand_id = item;
        that.goods_type.brand_type_list.push(brand_type);
      });
      var catIds = [];
      that.goods_type.goods_category_list.forEach(function(item, index) {
        var cat_id3 = item.parent_ids[2];
        if (catIds.indexOf(cat_id3) > -1) {
          that.goods_type.goods_category_list.splice(index, 1);
        } else {
          catIds.push(cat_id3);
        }
      });
      this.isLoading = true;
      if (this.$route.params.id) {
        //编辑
        updateGoodsType(this.goods_type).then(function(res) {
          if (res.status == 1) {
            that.$message.success({
              message: "保存成功",
              duration: 1000,
              onClose: function() {
                that.$router.push({
                  name: "goods_types"
                });
              }
            });
          } else if (res.status == -1) {
            that.$message.error("参数错误");
            that.errResult = res.result;
          } else {
            that.$message.error(res.msg);
          }
          that.isLoading = false;
        });
      } else {
        //添加
        addGoodsType(this.goods_type).then(function(res) {
          if (res.status == 1) {
            that.$message.success({
              message: "添加成功",
              duration: 1000,
              onClose: function() {
                that.$router.push({
                  name: "goods_types"
                });
              }
            });
          } else if (res.status == -1) {
            that.$message.error("参数错误");
            that.errResult = res.result;
          } else {
            that.$message.error(res.msg);
          }
          that.isLoading = false;
        });
      }
    },
    setGoodsAttribute(goods_attributes) {
      for (var i in goods_attributes) {
        if (goods_attributes[i].attr_input_type == 1) {
          goods_attributes[i].inputVisible = false;
          this.goods_attribute_select.push(goods_attributes[i]);
        }
        if (goods_attributes[i].attr_input_type == 2) {
          this.goods_attribute_input.push(goods_attributes[i]);
        }
      }
    },
    getGoodsType(id) {
      var that = this;
      getGoodsType({
        id: id
      }).then(function(res) {
        that.setGoodsAttribute(res.goods_attributes);
        for (var i in res.brand_type_list) {
          that.brand_ids.push(res.brand_type_list[i].brand_id);
        }
        that.goods_type = res;
      });
    },
    getGoodsCatCascade() {
      var that = this;
      getGoodsCategoryTree().then(function(res) {
        that.goodsCatCascade = res;
      });
    },

    //添加绑定的分类
    addBindGoodsCat() {
      this.goods_type.goods_category_list.push({});
    },
    //删除绑定的分类
    deleteBindGoodsCat(index, rows) {
      var that = this;
      if (typeof rows[index].id != "undefined") {
        deleteBindGoodsCat(rows[index].id).then(function(res) {
          if (res.status == 1) {
            rows.splice(index, 1);
          } else {
            that.$message.error("解除绑定失败，错误原因：" + res.msg);
          }
        });
      } else {
        rows.splice(index, 1);
      }
    },
    //删除规格
    deleteSpec(index, rows) {
      var that = this;
      if (typeof rows[index].id != "undefined") {
        deleteSpec(rows[index].id).then(function(res) {
          if (res.status == 1) {
            rows.splice(index, 1);
          } else {
            that.$message.error("删除失败，错误原因：" + res.msg);
          }
        });
      } else {
        rows.splice(index, 1);
      }
    },
    //删除属性,删除自定义属性
    deleteAttribute(index, rows) {
      var that = this;
      if (typeof rows[index].attr_id != "undefined") {
        deleteAttribute(rows[index].attr_id).then(function(res) {
          if (res.status == 1) {
            rows.splice(index, 1);
          } else {
            that.$message.error("删除失败，错误原因：" + res.msg);
          }
        });
      } else {
        rows.splice(index, 1);
      }
    },
    //添加规格
    addBindSpec() {
      this.goods_type.spec_list.push({
        order: 0
      });
    },
    //添加属性
    addAttributeSelect() {
      this.goods_attribute_select.push({
        order: 0,
        inputVisible: false,
        attr_value_list: [],
        attr_values: "",
        attr_input_type: 1
      });
    },
    //添加自定义属性值
    addAttributeInput() {
      this.goods_attribute_input.push({
        order: 0,
        attr_input_type: 2,
        attr_values: ""
      });
    },
    //获取某商品分类下的品牌列表
    getGoodsCatBrands() {
      var that = this;
      getGoodsCatBrands().then(function(res) {
        that.goods_category_brand = res;
      });
    },
    //删除属性值
    deleteAttributeVal(index, attribute) {
      var goods_attribute_select_row = this.goods_attribute_select[index]
        .attr_value_list;
      goods_attribute_select_row.splice(
        goods_attribute_select_row.indexOf(attribute),
        1
      );
    },
    showInput(selectIndex) {
      this.goods_attribute_select[selectIndex].inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm(index) {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.goods_attribute_select[index].attr_value_list.push(inputValue);
      }
      this.goods_attribute_select[
        index
      ].attr_values = this.goods_attribute_select[index].attr_value_list.join(
        ","
      );
      this.goods_attribute_select[index].inputVisible = false;
      this.inputValue = "";
    }
  }
};
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

>>> .el-input--small .el-input__inner {
  width: 250px;
}
>>> .name-input .el-input--small .el-input__inner {
  width: 180px;
}
>>> .sort-input .el-input--small .el-input__inner {
  width: 80px;
}
>>> .el-button--danger {
  margin-left: 10px;
}
>>> .el-button--primary {
  margin-top: 10px;
}
</style>
